/**
 * Created by Aboo on 2017/10/12.
 */

var escapeHTML = (function() {

    var chars = {
        '"': '&quot;',
        "'": '&#39;',
        '&': '&amp;',
        '/': '&#47;',
        '<': '&lt;',
        '>': '&gt;'
    };
    return function(text) {
        return String(text).replace(/[\"'\/<>]/g, function(char) {
            return chars[char];
        });
    };
}());

function escapeParme(value){
    var escapeParme = ['']; //parameters to escape
    var result = false;
    for(var escape_p in escapeParme){
        if(value == escapeParme[escape_p]){
            result = true;
        }
    }
    return result;
}

function removeEmptyValueJson(parameters){
    var res={};
    for(var o in parameters){
        if(parameters[o]==""){
            continue;
        }else{
            if(escapeParme(o) || typeof(parameters[o]) == "undefined"){
                res[o] = parameters[o];
            }else{
                res[o] = escapeHTML(parameters[o]);
            }
        }
    }
    return res;
}

var res_errMsg = 'سېستىمىدا تۆۋەندىكىەك خاتالىق كۆرۈلدى! قايتا سىناپ بىقىڭ ياكى سېستىما باشقۇرغۇچىلىرى بېلەن ئالاقىلىشىڭ .';

var  Net = function () {

    //use this to test on mobile
    // this.domain = "http://192.168.2.122:8080/tulpar/";

    this.domain = "http://localhost:8080/tulpar/";

    window.sessionStorage.setItem('domain',this.domain);

    this.get = function(url,parameters,fail,success){

        console.log("---GET Request---");
        console.log('requestURL:', this.domain+url);
        console.log('request params:', parameters);

        var rparms = removeEmptyValueJson(parameters);

        // 链接参数到url
        var full_url = this.domain + url + "?";
        var i = 0;
        $.each(rparms, function (key, value) {
            if (i == 0) {
                full_url += key + "=" + value;
            } else {
                full_url += "&" + key + "=" + value;
            }
        });

        // GET
        $.ajax({
            type: 'GET',
            url: full_url,
            dataType: 'json'
            // TODO：user authorization
            // beforeSend: function(xhr) {
            //     if (sessionStorage.getItem('login_user')!=null) {
            //         console.log('user:%o', user);
            //         xhr.setRequestHeader('BasicAuthUsername', user.userId);
            //     }
            // }
        }).fail(function (error) {
            dia.alert('ئەسكەرتىش','تور مۇھىيتىدا خاتالىق كۆرۈلدى!سەل تۇرۇپ قايتا سىناپ بىقىڭ !',['بىلدىم'],'fa fa-exclamation',function () {

            });
            fail(error);
            console.error(error);
        }).done(function (response) {
            console.log("response data: ",response);
            //response.code 非零,就不调用success (说明系统出了问题)
            if(response.code != 0){
                dia.alert('ئەپسۇس',res_errMsg,['ئالاقىلىشىمەن','ۋاز كىچىمەن'],'fa fa-times',function (btn_name) {
                    if(btn_name == 'ئالاقىلىشىمەن'){ $(".sidebar .nav-item #contact").click(); }
                    if(btn_name == 'ۋاز كىچىمەن'){ /* do nothing */ }
                },response);
            }
            //只有response.code=0,才调用
            success(response);
        });

    }


    this.post = function (url, parameters, fail, success,params) {
        console.log('---POST Request---');
        console.log('requestURL: ', this.domain+url);
        console.log('request params: ', parameters);
        var async = true;
        if(params && typeof(params.asyncPra) != "undefined"){
            async = params.asyncPra;
        }

        var full_url = this.domain + url;
        // var rparms = removeEmptyValueJson(parameters);

        // POST
        $.ajax({
            type: 'POST',
            url: full_url,
            dataType: 'json',
            contentType:'application/json',
            data: JSON.stringify(parameters),
            async:async
            // TODO: user Authorization
            // beforeSend: function(xhr) {
            //     if (sessionStorage.getItem('login_user')!=null) {
            //         xhr.setRequestHeader('BasicAuthUsername', user.userId);
            //     }
            // }
        }).fail(function (error) {
            dia.alert('ئەسكەرتىش','تور مۇھىيتىدا خاتالىق كۆرۈلدى!سەل تۇرۇپ قايتا سىناپ بىقىڭ !',['بىلدىم'],'fa fa-exclamation',function () {

            });
            fail(error);
            console.error(error);
        }).done(function (response) {
            console.log("response data: ",response);
            //response.code 非零,就不调用success (说明系统出了问题)
            if(response.code != 0){
                dia.alert('ئەپسۇس',res_errMsg,['ئالاقىلىشىمەن','ۋاز كىچىمەن'],'fa fa-times',function (btn_name) {
                    if(btn_name == 'ئالاقىلىشىمەن'){ $(".sidebar .nav-item #contact").click(); }
                    if(btn_name == 'ۋاز كىچىمەن'){ /* do nothing */ }
                },response);
            }
            //只有response.code=0,才调用
            success(response);
        });

    }

}

var net = new Net();
